<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TaskFlow - Modern Todo List</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link
      href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
    />

    <!-- Tailwind Configuration -->
    <script>
      tailwind.config = {
        darkMode: "class",
        theme: {
          extend: {
            colors: {
              primary: "#4F46E5", // Indigo
              secondary: "#10B981", // Emerald
              accent: "#F59E0B", // Amber
              danger: "#EF4444", // Red
              dark: {
                100: "#1F2937",
                200: "#111827",
                300: "#030712",
              },
              light: {
                100: "#F9FAFB",
                200: "#F3F4F6",
                300: "#E5E7EB",
              },
            },
            fontFamily: {
              inter: ["Inter", "system-ui", "sans-serif"],
            },
          },
        },
      };
    </script>

    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .task-enter {
          animation: taskIn 0.3s ease-out forwards;
        }
        .task-exit {
          animation: taskOut 0.3s ease-in forwards;
        }
        @keyframes taskIn {
          0% {
            opacity: 0;
            transform: translateY(10px);
          }
          100% {
            opacity: 1;
            transform: translateY(0);
          }
        }
        @keyframes taskOut {
          0% {
            opacity: 1;
            transform: translateY(0);
          }
          100% {
            opacity: 0;
            transform: translateY(10px);
          }
        }
        .pulse-subtle {
          animation: pulseSubtle 2s infinite;
        }
        @keyframes pulseSubtle {
          0%,
          100% {
            opacity: 1;
          }
          50% {
            opacity: 0.7;
          }
        }
      }
    </style>
  </head>

  <body
    class="font-inter bg-gradient-to-br from-light-100 to-light-200 dark:from-dark-200 dark:to-dark-300 min-h-screen text-gray-800 dark:text-gray-200 transition-all duration-300"
  >
    <!-- Theme Toggle Button -->
    <button
      id="theme-toggle"
      class="fixed top-6 right-6 p-3 rounded-full bg-white/80 dark:bg-dark-100/80 shadow-lg backdrop-blur-sm text-primary hover:bg-white dark:hover:bg-dark-100 transition-all duration-300 z-50"
    >
      <i class="fa fa-sun-o dark:hidden text-xl" aria-hidden="true"></i>
      <i class="fa fa-moon-o hidden dark:block text-xl" aria-hidden="true"></i>
    </button>

    <div class="container mx-auto px-4 py-12 max-w-3xl">
      <!-- Header Section -->
      <header class="mb-10 text-center">
        <h1
          class="text-[clamp(2rem,5vw,3rem)] font-bold text-gray-900 dark:text-white mb-2 flex items-center justify-center"
        >
          <i
            class="fa fa-check-square-o text-primary mr-3"
            aria-hidden="true"
          ></i>
          TaskFlow
        </h1>
        <p class="text-gray-600 dark:text-gray-400 text-lg">
          Organize your tasks efficiently
        </p>
      </header>

      <!-- Main Todo Container -->
      <div
        class="bg-white dark:bg-dark-100 rounded-2xl shadow-xl overflow-hidden transition-all duration-300 transform hover:shadow-2xl"
      >
        <!-- Add Task Form -->
        <div class="p-6 border-b border-gray-200 dark:border-gray-700">
          <form id="add-task-form" class="flex gap-3">
            <input
              type="text"
              id="new-task-input"
              placeholder="Add a new task..."
              class="flex-1 px-4 py-3 rounded-lg bg-light-200 dark:bg-dark-200 border border-transparent focus:border-primary focus:ring-2 focus:ring-primary/20 outline-none transition-all duration-300"
              required
            />
            <button
              type="submit"
              class="px-5 py-3 bg-primary hover:bg-primary/90 text-white rounded-lg font-medium transition-all duration-300 transform hover:scale-105 active:scale-95 flex items-center gap-2"
            >
              <i class="fa fa-plus" aria-hidden="true"></i>
              <span>Add</span>
            </button>
          </form>
        </div>

        <!-- Task Filters -->
        <div
          class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex flex-wrap gap-2"
        >
          <button
            class="filter-btn active px-4 py-2 rounded-full text-sm font-medium bg-primary/10 text-primary transition-all duration-300"
            data-filter="all"
          >
            All
          </button>
          <button
            class="filter-btn px-4 py-2 rounded-full text-sm font-medium bg-light-200 dark:bg-dark-200 hover:bg-light-300 dark:hover:bg-dark-300 transition-all duration-300"
            data-filter="active"
          >
            Active
          </button>
          <button
            class="filter-btn px-4 py-2 rounded-full text-sm font-medium bg-light-200 dark:bg-dark-200 hover:bg-light-300 dark:hover:bg-dark-300 transition-all duration-300"
            data-filter="completed"
          >
            Completed
          </button>
        </div>

        <!-- Tasks List -->
        <div
          id="tasks-container"
          class="divide-y divide-gray-200 dark:divide-gray-700 max-h-[500px] overflow-y-auto"
        >
          <!-- Empty State -->
          <div id="empty-state" class="p-12 text-center">
            <div
              class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/10 text-primary mb-4"
            >
              <i class="fa fa-tasks text-2xl" aria-hidden="true"></i>
            </div>
            <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-2">
              No tasks yet
            </h3>
            <p class="text-gray-600 dark:text-gray-400">
              Add a new task to get started
            </p>
          </div>

          <!-- Tasks will be added here dynamically -->
        </div>

        <!-- Task Summary & Actions -->
        <div
          id="task-summary"
          class="px-6 py-4 border-t border-gray-200 dark:border-gray-700 flex flex-wrap justify-between items-center gap-3 hidden"
        >
          <div class="text-sm text-gray-600 dark:text-gray-400">
            <span id="active-tasks-count">0</span> items left
          </div>
          <button
            id="clear-completed"
            class="text-sm text-gray-600 dark:text-gray-400 hover:text-danger dark:hover:text-danger transition-colors duration-300"
          >
            Clear completed
          </button>
        </div>
      </div>

      <!-- Instructions -->
      <div
        class="mt-8 p-4 bg-white/80 dark:bg-dark-100/80 backdrop-blur-sm rounded-xl shadow-md"
      >
        <h3 class="text-center font-medium text-gray-900 dark:text-white mb-2">
          Quick Tips
        </h3>
        <ul
          class="text-sm text-gray-600 dark:text-gray-400 grid grid-cols-1 md:grid-cols-2 gap-2"
        >
          <li class="flex items-center">
            <i
              class="fa fa-check-circle text-secondary mr-2"
              aria-hidden="true"
            ></i>
            <span>Click on a task to mark it as complete</span>
          </li>
          <li class="flex items-center">
            <i class="fa fa-pencil text-accent mr-2" aria-hidden="true"></i>
            <span>Double-click to edit a task</span>
          </li>
          <li class="flex items-center">
            <i class="fa fa-trash text-danger mr-2" aria-hidden="true"></i>
            <span>Hover and click X to delete a task</span>
          </li>
          <li class="flex items-center">
            <i class="fa fa-filter text-primary mr-2" aria-hidden="true"></i>
            <span>Use filters to manage your view</span>
          </li>
        </ul>
      </div>

      <!-- Footer -->
      <footer
        class="mt-12 text-center text-gray-600 dark:text-gray-400 text-sm"
      >
        <p>TaskFlow © 2023 | A modern todo list application</p>
      </footer>
    </div>

    <!-- JavaScript for Todo List Functionality -->
    <script>
      // DOM Elements
      const addTaskForm = document.getElementById("add-task-form");
      const newTaskInput = document.getElementById("new-task-input");
      const tasksContainer = document.getElementById("tasks-container");
      const emptyState = document.getElementById("empty-state");
      const taskSummary = document.getElementById("task-summary");
      const activeTasksCount = document.getElementById("active-tasks-count");
      const clearCompletedBtn = document.getElementById("clear-completed");
      const filterBtns = document.querySelectorAll(".filter-btn");
      const themeToggle = document.getElementById("theme-toggle");

      // State
      let tasks = JSON.parse(localStorage.getItem("tasks")) || [];
      let currentFilter = "all";

      // Initialize
      document.addEventListener("DOMContentLoaded", () => {
        // Load theme preference
        loadThemePreference();

        // Render tasks
        renderTasks();

        // Update UI state
        updateUIState();
      });

      // Event Listeners
      addTaskForm.addEventListener("submit", (e) => {
        e.preventDefault();
        const taskText = newTaskInput.value.trim();

        if (taskText) {
          addTask(taskText);
          newTaskInput.value = "";
          newTaskInput.focus();
        }
      });

      clearCompletedBtn.addEventListener("click", clearCompletedTasks);

      filterBtns.forEach((btn) => {
        btn.addEventListener("click", () => {
          // Update active button styling
          filterBtns.forEach((b) => {
            b.classList.remove("active", "bg-primary/10", "text-primary");
            b.classList.add(
              "bg-light-200",
              "dark:bg-dark-200",
              "hover:bg-light-300",
              "dark:hover:bg-dark-300"
            );
          });

          btn.classList.add("active", "bg-primary/10", "text-primary");
          btn.classList.remove(
            "bg-light-200",
            "dark:bg-dark-200",
            "hover:bg-light-300",
            "dark:hover:bg-dark-300"
          );

          // Update filter
          currentFilter = btn.dataset.filter;
          renderTasks();
        });
      });

      themeToggle.addEventListener("click", toggleTheme);

      // Functions
      function addTask(text) {
        const newTask = {
          id: Date.now().toString(),
          text: text,
          completed: false,
          createdAt: new Date().toISOString(),
        };

        tasks.unshift(newTask);
        saveTasks();
        renderTasks();
        updateUIState();

        // Add animation to the new task
        const newTaskElement = document.querySelector(
          `[data-id="${newTask.id}"]`
        );
        if (newTaskElement) {
          newTaskElement.classList.add("task-enter");
        }
      }

      function toggleTaskCompletion(id) {
        tasks = tasks.map((task) =>
          task.id === id ? { ...task, completed: !task.completed } : task
        );
        saveTasks();
        renderTasks();
        updateUIState();
      }

      function editTask(id, newText) {
        newText = newText.trim();
        if (!newText) {
          deleteTask(id);
          return;
        }

        tasks = tasks.map((task) =>
          task.id === id ? { ...task, text: newText } : task
        );
        saveTasks();
        renderTasks();
      }

      function deleteTask(id) {
        const taskElement = document.querySelector(`[data-id="${id}"]`);
        if (taskElement) {
          taskElement.classList.add("task-exit");
          taskElement.addEventListener(
            "animationend",
            () => {
              tasks = tasks.filter((task) => task.id !== id);
              saveTasks();
              renderTasks();
              updateUIState();
            },
            { once: true }
          );
        } else {
          tasks = tasks.filter((task) => task.id !== id);
          saveTasks();
          renderTasks();
          updateUIState();
        }
      }

      function clearCompletedTasks() {
        const completedTasks = tasks.filter((task) => task.completed);

        if (completedTasks.length === 0) return;

        // Animate out completed tasks
        let completedCount = 0;
        completedTasks.forEach((task) => {
          const taskElement = document.querySelector(`[data-id="${task.id}"]`);
          if (taskElement) {
            taskElement.classList.add("task-exit");
            taskElement.addEventListener(
              "animationend",
              () => {
                completedCount++;
                if (completedCount === completedTasks.length) {
                  tasks = tasks.filter((task) => !task.completed);
                  saveTasks();
                  renderTasks();
                  updateUIState();
                }
              },
              { once: true }
            );
          }
        });
      }

      function renderTasks() {
        // Clear current tasks except empty state
        Array.from(tasksContainer.children).forEach((child) => {
          if (child.id !== "empty-state") {
            tasksContainer.removeChild(child);
          }
        });

        // Filter tasks based on current filter
        let filteredTasks = tasks;
        if (currentFilter === "active") {
          filteredTasks = tasks.filter((task) => !task.completed);
        } else if (currentFilter === "completed") {
          filteredTasks = tasks.filter((task) => task.completed);
        }

        // Render filtered tasks
        filteredTasks.forEach((task) => {
          const taskElement = createTaskElement(task);
          tasksContainer.appendChild(taskElement);
        });

        // Show/hide empty state
        emptyState.style.display =
          filteredTasks.length === 0 ? "block" : "none";
      }

      function createTaskElement(task) {
        const taskElement = document.createElement("div");
        taskElement.className =
          "p-4 flex items-center gap-3 hover:bg-light-100 dark:hover:bg-dark-200 transition-colors duration-200";
        taskElement.dataset.id = task.id;

        taskElement.innerHTML = `
                <button class="task-toggle w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0 ${
                  task.completed
                    ? "bg-secondary text-white"
                    : "border-2 border-gray-300 dark:border-gray-600 hover:border-primary dark:hover:border-primary"
                } transition-all duration-300">
                    ${
                      task.completed
                        ? '<i class="fa fa-check text-sm" aria-hidden="true"></i>'
                        : ""
                    }
                </button>
                <span class="task-text flex-1 ${
                  task.completed
                    ? "line-through text-gray-500 dark:text-gray-400"
                    : ""
                } transition-all duration-300">${escapeHTML(task.text)}</span>
                <button class="task-delete p-2 text-gray-400 hover:text-danger transition-colors duration-200 opacity-0 group-hover:opacity-100">
                    <i class="fa fa-times" aria-hidden="true"></i>
                </button>
            `;

        // Add event listeners
        const toggleBtn = taskElement.querySelector(".task-toggle");
        const taskText = taskElement.querySelector(".task-text");
        const deleteBtn = taskElement.querySelector(".task-delete");

        toggleBtn.addEventListener("click", () =>
          toggleTaskCompletion(task.id)
        );

        deleteBtn.addEventListener("click", () => deleteTask(task.id));

        // Double click to edit
        taskText.addEventListener("dblclick", () =>
          enableTaskEditing(taskElement, task)
        );

        // Make delete button visible on hover
        taskElement.classList.add("group");

        return taskElement;
      }

      function enableTaskEditing(taskElement, task) {
        const taskTextElement = taskElement.querySelector(".task-text");
        const currentText = task.text;

        const editInput = document.createElement("input");
        editInput.type = "text";
        editInput.value = currentText;
        editInput.className =
          "flex-1 px-3 py-2 rounded-lg border-2 border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 bg-light-100 dark:bg-dark-200";

        // Replace text with input
        taskElement.replaceChild(editInput, taskTextElement);

        // Focus and select text
        editInput.focus();
        editInput.select();

        // Handle blur or enter key to save
        const saveEdit = () => {
          editTask(task.id, editInput.value);
        };

        editInput.addEventListener("blur", saveEdit);
        editInput.addEventListener("keydown", (e) => {
          if (e.key === "Enter") {
            editInput.blur();
          } else if (e.key === "Escape") {
            // Revert on escape
            taskElement.replaceChild(taskTextElement, editInput);
          }
        });
      }

      function updateUIState() {
        // Update active tasks count
        const activeCount = tasks.filter((task) => !task.completed).length;
        activeTasksCount.textContent = activeCount;

        // Show/hide summary
        taskSummary.classList.toggle("hidden", tasks.length === 0);

        // Enable/disable clear completed button
        const hasCompleted = tasks.some((task) => task.completed);
        clearCompletedBtn.disabled = !hasCompleted;
        clearCompletedBtn.classList.toggle("opacity-50", !hasCompleted);
        clearCompletedBtn.classList.toggle("cursor-not-allowed", !hasCompleted);
      }

      function saveTasks() {
        localStorage.setItem("tasks", JSON.stringify(tasks));
      }

      function toggleTheme() {
        const isDark = document.documentElement.classList.toggle("dark");
        localStorage.setItem("theme", isDark ? "dark" : "light");
      }

      function loadThemePreference() {
        const savedTheme = localStorage.getItem("theme");
        const prefersDark = window.matchMedia(
          "(prefers-color-scheme: dark)"
        ).matches;

        if (savedTheme === "dark" || (!savedTheme && prefersDark)) {
          document.documentElement.classList.add("dark");
        }
      }

      // Helper function to escape HTML
      function escapeHTML(str) {
        return str
          .replace(/&/g, "&amp;")
          .replace(/</g, "&lt;")
          .replace(/>/g, "&gt;")
          .replace(/"/g, "&quot;")
          .replace(/'/g, "&#039;");
      }
    </script>
  </body>
</html>
